#include <stdio.h>
#include <windows.h>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
#define WIDTH 20
#define HEIGHT 20
typedef struct{
	int x;
	int y;
}Snake;
typedef struct{
	int x;
	int y;
}Food;
Snake snake[100];
int  snakeLength;
Food food;
int direction;
int gameOver;
void gotoxy(int x,int y){
	COORD coord;
	coord.X=x;
	coord.Y=y;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void hideCursor() {
	CONSOLE_CURSOR_INFO cursor_info = {1, 0};
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void initGame(){
	snakeLength = 3;
	snake[0].x = WIDTH / 2;
	snake[0].y = HEIGHT / 2;
	for (int i = 1; i < snakeLength; i++) {
		snake[i].x = snake[i - 1].x - 1;
		snake[i].y = snake[i - 1].y;
	}
	srand(time(NULL));
	food.x = rand() % (WIDTH - 2) + 1;
	food.y = rand() % (HEIGHT - 2) + 1;
	direction = 1;
	gameOver = 0;
}
void draw() {
	system("cls");
	for (int i = 0; i < WIDTH; i++) {
		printf("#");
	}
	printf("\n");
	for (int i = 0; i < HEIGHT - 2; i++) {
		for (int j = 0; j < WIDTH; j++) {
			if (j == 0 || j == WIDTH - 1) {
				printf("#");
			} else if (j == food.x && i + 1 == food.y) {
				printf("F");
			} else {
				int isSnake = 0;
				for (int k = 0; k < snakeLength; k++) {
					if (snake[k].x == j && snake[k].y == i + 1) {
						printf("O");
						isSnake = 1;
						break;
					}
				}
				if (!isSnake) {
					printf(" ");
				}
			}
		}
		printf("\n");
	}
	for (int i = 0; i < WIDTH; i++) {
		printf("#");
	}
	printf("\n");
}
void input() {
	if (_kbhit()) {
		switch (_getch()) {
			case 72: // 上
			if (direction != 4) direction = 3;
			break;
			case 80: // 下
			if (direction != 3) direction = 4;
			break;
			case 75: // 左
			if (direction != 1) direction = 2;
			break;
			case 77: // 右
			if (direction != 2) direction = 1;
			break;
			case 27: // ESC 键退出
			gameOver = 1;
			break;
		}
	}
}
void logic(){
	for (int i = snakeLength - 1; i > 0; i--) {
		snake[i].x = snake[i - 1].x;
		snake[i].y = snake[i - 1].y;
	}
	switch (direction) {
	case 1:
		snake[0].x++;
		break;
	case 2:
		snake[0].x--;
		break;
	case 3:
		snake[0].y--;
		break;
	case 4:
		snake[0].y++;
		break;
	}
	if (snake[0].x == food.x && snake[0].y == food.y) {
		snakeLength++;
		food.x = rand() % (WIDTH - 2) + 1;
		food.y = rand() % (HEIGHT - 2) + 1;
	}
	if (snake[0].x == 0 || snake[0].x == WIDTH - 1 || snake[0].y == 0 || snake[0].y == HEIGHT - 1) {
		gameOver = 1;
	}
	for (int i = 1; i < snakeLength; i++) {
		if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
			gameOver = 1;
		}
	}
}

int main() {
	initGame();
	hideCursor();
	while (!gameOver) {
		draw();
		input();
		logic();
		Sleep(100);
	}
	gotoxy(0, HEIGHT);
	printf("Game Over!\n");
	return 0;
}
